// 版权归 瞄你个汪 所有。使用本代码应遵守相关法律法规和Apache 2.0开源许可要求。
package top.geeke.toolkit;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import lombok.Getter;
import top.geeke.config.AppConfiguration;

/**
 * <p>
 * 加解密工具
 * </p>
 *
 * @author 瞄你个汪
 * @since 2024/6/1 7:43
 */
public class EncryptTool {

    @Getter
    private final static SM2 sm2;

    static {
        AppConfiguration configuration = SpringBeanManager.getBean(AppConfiguration.class);
        AppConfiguration.CryptogramOption cryptogram = configuration.getCryptogram();
        sm2 = new SM2(cryptogram.getPrivateKey(), cryptogram.getPublicKey());
    }

    /**
     * 获取公钥
     */
    public static String getPublicKeyStr() {
        return sm2.getPublicKey().toString();
    }

    /**
     * 公钥加密
     */
    public static String encryptHex(String data) {
        return sm2.encryptHex(data, KeyType.PublicKey);
    }

    /**
     * 私钥解密
     */
    public static String decryptStr(String data) {
        return sm2.decryptStr(data, KeyType.PrivateKey);
    }

    /**
     * 签名
     */
    public static String signHex(String data) {
        return sm2.signHex(HexUtil.encodeHexStr(data));
    }

    /**
     * 验签
     */
    public static boolean verifyHex(String data, String singHex) {
        return sm2.verifyHex(HexUtil.encodeHexStr(data), singHex);
    }

    /**
     * 公钥加密
     */
    public static byte[] encrypt(byte[] bytes) {
        return sm2.encrypt(bytes, KeyType.PublicKey);
    }

    /**
     * 私钥解密
     */
    public static byte[] decrypt(byte[] bytes) {
        return sm2.decrypt(bytes, KeyType.PrivateKey);
    }

    /**
     * 签名
     */
    public static byte[] sign(byte[] bytes) {
        return sm2.sign(bytes);
    }

    /**
     * 验签
     */
    public static boolean verifyHex(byte[] bytes, byte[] singHex) {
        return sm2.verify(bytes, singHex);
    }
}
